<template>
  <div class="homePage">
    <div class="info">
      <el-form>
        <el-form-item>
          <img :src="imgUrl" class="avatar" />
        </el-form-item>
        <el-form-item>
          <span
            style="
              position: relative;
              top: -178px;
              left: 198px;
              font-size: 20px;
            "
            >欢迎！{{ currentUser.name }}</span
          >
          <el-rate v-model="value1" disabled class="rate" />
        </el-form-item>
        <el-form-item>
          <el-button type="success" class="online">在线 </el-button>
        </el-form-item>
        <el-form-item class="max-btn">
          <el-button type="info" @click="dialog1 = true">咨询设置</el-button>
          <el-dialog v-model="dialog1" class="ingo-dialog">
            <el-form>
              <el-form-item
                label="请输入最大咨询数"
                style="position: relative; left: 31%; padding-bottom: 20px"
              >
                <el-col :span="10">
                  <el-input-number v-model="currentUser.maxConsults">{{
                    currentUser.maxConsults
                  }}</el-input-number>
                </el-col>
              </el-form-item>

              <el-button
                type="primary"
                @click="
                  commmit();
                  dialog1 = flase;
                "
                >确认</el-button
              >
              <el-button @click="dialog1 = flase">取消</el-button>
            </el-form>
          </el-dialog>
        </el-form-item>
      </el-form>
    </div>
    <el-card class="card-table">
      <template #header>
        <div class="card-header">
          <span class="head-title"> 在线咨询师 </span>
          <el-pagination
            small
            background
            v-model:currentPage="queryForm_consultant.page"
            v-model:page-size="queryForm_consultant.size"
            layout="total, prev, pager, next, jumper"
            :total="total_consultant"
            @current-change="handleCurrentChange_consultant"
          />
        </div>
      </template>
      <td v-if="tableData_consultant.length == 0">
        <span style="position: relative; left: 258%; font-size: 20px"
          >暂无咨询师在线</span
        >
      </td>
      <el-row>
        <td
          v-for="(item, index) in tableData_consultant.slice(0, 3)"
          :key="index"
        >
          <el-card v-if="item.isOnline == 1" class="card-item1">
            <span style="color: black; font-weight: 400; font-size: 16px"
              >{{ item.name }}
            </span>
          </el-card>
        </td></el-row
      >
      <el-row>
        <td
          v-for="(item, index) in tableData_consultant.slice(3, 6)"
          :key="index"
        >
          <el-card v-if="item.isOnline == 1" class="card-item1">
            <span
              v-if="item.isOnline == 1"
              style="color: black; font-weight: 400; font-size: 16px"
              >{{ item.name }}
            </span>
          </el-card>
        </td>
      </el-row>

      <el-row>
        <td
          v-for="(item, index) in tableData_consultant.slice(6, 9)"
          :key="index"
        >
          <el-card v-if="item.isOnline == 1" class="card-item1">
            <span style="color: black; font-weight: 400; font-size: 16px"
              >{{ item.name }}
            </span>
          </el-card>
        </td>
      </el-row>
    </el-card>
    <div class="times">
      <el-table
        :data="tableData"
        stripe
        :cell-style="{ 'text-align': 'center' }"
        style="width: 100% height: 100%"
      >
        <el-table-column prop="times" label="今日咨询数" />
        <el-table-column prop="duration" label="今日咨询时长" />
        <el-table-column prop="conversation" label="当前会话数量" />
      </el-table>
    </div>
    <div class="Scheduling" v-loading="!showCalendar">
      <el-calendar v-if="showCalendar">
        <template #dateCell="{ data }">
          <span v-if="calendar.indexOf(data.day) > -1" style="color: green"
            >值班</span
          >
        </template>
      </el-calendar>
    </div>
    <div class="record-table">
      <el-form v-loading="!showData">
        <el-form-item label="最近完成的咨询" class="item">
          <el-button class="detail" type="text" @click="showDetails"
            >查看全部</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-table
            v-if="showData"
            :data="currentData"
            stripe
            style="width: 100%"
            border="1px"
            max-height="160"
          >
            <el-table-column prop="visitorName" label="访客姓名" width="180" />
            <el-table-column
              prop="counsellorName"
              label="咨询师姓名"
              width="180"
            />
            <el-table-column prop="duration" label="咨询时长" width="180" />
            <el-table-column prop="startTime" label="咨询日期" />
            <el-table-column prop="rating" label="咨询评级">
              <template v-slot="scope">
                <el-rate disabled v-model="scope.row.rating" />
              </template>
            </el-table-column>
            <el-table-column prop="evaluation" label="咨询评价" />
            <el-table-column prop="option" label="操作">
              <template v-slot="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="
                    getDetails(scope.row.conversationID);
                    showDialog = true;
                  "
                  >查看详情</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="exportSingle(scope.row.conversationID)"
                  >导出记录</el-button
                >
              </template>
            </el-table-column>
            <template v-slot:empty>
              <p :class="{ 'el-table-empty-p': tableText }">{{ tableText }}</p>
            </template>
          </el-table>
        </el-form-item>
      </el-form>
      <el-dialog v-model="showDialog" v-loading="!showTable">
        <div v-loading="!showTable">
          <el-form v-if="showTable">
            <el-form-item v-for="item in chatData" :key="item">
              <img :src="item.avatar" style="width: 40px; height: 40px" />
              <div style="text-align: left">
                <span :style="selectColor(item.name)">{{ item.name }}</span>
                <div class="pop" v-if="item.flag == 0">
                  <div class="arrow"></div>
                  {{ item.message }}
                </div>
                <div
                  class="pop"
                  v-else-if="item.flag == 1"
                  style="background-color: #90939994"
                >
                  <div
                    class="arrow"
                    style="border-color: #fff #90939994 #fff #fff"
                  ></div>
                  {{ item.message }}
                </div>
                <div
                  class="pop"
                  v-else-if="item.flag == 2"
                  style="background-color: #29c702d1"
                >
                  <div
                    class="arrow"
                    style="border-color: #fff #29c702d1 #fff #fff"
                  ></div>
                  {{ item.message }}
                </div>
              </div>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="showDialog = false">确认</el-button>
          <el-button @click="showDialog = false">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts">
import { recordData, recordSearch, user, userList } from "@/interface/type";
import router from "@/router";
import {
  getArrange,
  getInfo,
  getRecord,
  getDuration,
  getDetail,
  getExportSingle,
  editInfo,
} from "@/service/api";
import { getConsultantList, searchSchedule_month } from "@/service/api_admin";
import {
  h,
  ref,
  defineComponent,
  reactive,
  unref,
  getCurrentScope,
  getCurrentInstance,
} from "vue";
export default defineComponent({
  setup() {
    let queryForm = ref({
      page: 1,
      size: 10,
      role: 1,
      name: "",
    });
    let currentData = reactive([{}]);
    let showCalendar = ref(false);
    let currentUser = ref(new user());
    let searchOption: recordSearch = {};
    let showTable = ref(false);
    let imgUrl = ref("");
    const tableText = ref("暂无记录");
    const params: string[] = [];
    let currentConsultant = reactive([{}]);
    let showDialog = ref(false);
    let dialog1 = ref(false);
    let value1 = ref(3);
    let calendar: string[] = [];
    let showData = ref(false);
    let currentList = ref({});
    let tableData = reactive([
      {
        times: 0, // 咨询次数
        duration: "", // 咨询时长
        conversation: 0, // 当前会话数
      },
    ]);
    const dealRecord = (res: any[]) => {
      showData.value = false;
      res = Array.from(res);
      currentData.length = 0;
      res.forEach((item: any) => {
        let temp: recordData = {};
        temp.conversationID = item.conversationID;
        temp.counsellorName = item.counsellorInfo.name;
        temp.visitorName = item.visitorInfo.name;
        temp.startTime = item.startTime;
        temp.endTime = item.endTime;
        if (
          new Date(item.startTime).getTime() > new Date(item.endTime).getTime()
        ) {
          temp.duration = "正在咨询中";
        } else {
          const seconds =
            (new Date(item.endTime).getTime() -
              new Date(item.startTime).getTime()) /
            1000;
          const hours = Math.floor(seconds / 3600);
          const minutes = Math.floor((seconds - hours * 3600) / 60);
          const second = seconds % 60;
          temp.duration = hours + ":" + minutes + ":" + second;
        }
        if (item.evaluation != null) {
          temp.rating = item.evaluation.rating;
          if (item.evaluation.evaluation) {
            temp.evaluation = item.evaluation.evaluation;
          } else {
            temp.evaluation = "暂无评价";
          }
        } else {
          temp.evaluation = "暂无评价";
        }

        currentData.push(temp);
        showData.value = true;
      });
      showData.value = true;
    };

    const selectColor = (item: any) => {
      const nameList: any[] = [];
      chatData.forEach((val: any) => {
        if (nameList.findIndex((e) => e == val.name) == -1)
          nameList.push(val.name);
      });
      let second: any;
      if (item == nameList[0]) {
        return {
          paddingLeft: "33px",
          color: "#2d90af",
        };
      } else if (item == nameList[1]) {
        return {
          paddingLeft: "33px",
          color: "#86878b",
        };
      } else if (nameList[2] && item == nameList[2]) {
        return {
          paddingLeft: "33px",
          color: "#32861d",
        };
      }
    };
    const getPageInfo = async () => {
      await getInfo().then(async (response) => {
        const res: any = response.data;
        currentUser.value = new user(res.result);
        console.log("currentUser", currentUser);
        searchOption.cname = currentUser.value.name; //获取当前用户的咨询记录
        searchOption.size = 1000;
        if (currentUser.value.avatar === "") {
          currentUser.value.avatar = "default.jpg";
          imgUrl.value = require("@/assets/" + currentUser.value.avatar);
        } else {
          imgUrl.value = currentUser.value.avatar;
        }

        const today = new Date();
        const year = today.getFullYear();
        const month = today.getMonth() + 1;
        const day: number = today.getDate();
        let monthStr = "";
        let dayStr = "";
        if (month < 10) {
          monthStr = "0" + month;
        } else {
          monthStr = "" + month;
        }
        const list: number[] = [];
        const leap_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        const common_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        //判断平闰年
        let maxDay = 0;
        if (year % 100 == 0) {
          if (year % 400 == 0) {
            maxDay = leap_month[month];
          } else {
            maxDay = common_month[month];
          }
        } else {
          if (year % 4 == 0) {
            maxDay = leap_month[month];
          } else {
            maxDay = common_month[month];
          }
        }
        for (let num = 1; num <= maxDay; num++) {
          if (num < 10) {
            dayStr = "0" + num;
          } else {
            dayStr = "" + num;
          }
          const param = "2022-" + monthStr + "-" + dayStr;
          params.push(param);
          let option = new Date(param).getTime();
          option = option / 1000; //13位时间戳转换为10位
          list.push(option);
        }
        if (currentUser) {
          await searchSchedule_month(list).then((res) => {
            const arrange: any[] = res.data.result;
            let i = 0;
            arrange.forEach((item) => {
              console.log(item);
              const counsellors = item.counsellors;
              if (
                counsellors.findIndex(
                  (val: any) =>
                    val.counsellorID === currentUser.value.counsellorID
                ) !== -1
              ) {
                calendar.push(params[i]);
              }
              i++;
            });
          });
          console.log("calendar", calendar);
          showCalendar.value = true;
        }
      });

      getDuration().then((res) => {
        const result = res.data.result;
        const count = result.totalCount;
        const duration =
          "" + result.hour + ": " + result.minute + ": " + result.second + "";
        const conversation = result.inConversationCnt;
        tableData.length = 0;
        tableData.push({
          times: count,
          duration: duration,
          conversation: conversation,
        });
      });
      console.log("tableData", tableData[0]);
      console.log("searchOption", searchOption);
      setTimeout(() => {
        getRecord(searchOption).then((res) => {
          console.log("data", res.data);
          dealRecord(res.data.result);
        });
      }, 100);
      return 1;
    };
    const commmit = () => {
      editInfo(currentUser.value).then();
    };
    const isSelect = (day: any) => {
      if (calendar.findIndex((item) => item === day) !== -1) {
        return 1;
      } else {
        return 0;
      }
    };
    //查看全部记录
    const showDetails = () => {
      const cname = searchOption.cname;
      router.push("/history");
    };

    let chatData = reactive<any>([{}]);
    // 查看详情
    const getDetails = async (item: string) => {
      showTable.value = false;
      await getDetail(item).then((res) => {
        const result = res.data.result;
        chatData.length = 0;
        let flag = -1;
        result.forEach((val: any, index: number) => {
          const name = val.From_Account;
          let avatar = "";
          if (val.Avatar) {
            avatar = val.Avatar;
          } else {
            const temp = "default.jpg";
            avatar = require("@/assets/" + temp);
          }
          let message = "";
          val.MsgBody.forEach((mes: any) => {
            if (mes.MsgType == "TIMImageElem") {
              message = message + "[图片]" + "\n";
            } else if (mes.MsgType == "TIMSoundElem") {
              message = message + "[语音]" + "\n";
            } else if (mes.MsgType == "TIMCustomElem") {
              message = message + "[评价]" + "\n";
            } else {
              message = message + mes.MsgContent.Text + "\n";
            }
          });
          const num = chatData.findIndex((val: any) => val.name == name);
          console.log("chatData", chatData);
          let currentFlage = 0;
          if (num != -1) {
            currentFlage = chatData[num].flag;
          } else {
            flag += 1;
            currentFlage = flag;
          }

          chatData.push({
            avatar: avatar,
            name: name,
            message: message,
            flag: currentFlage,
          });
        });
        showTable.value = true;
      });
    };
    // 导出单条
    const exportSingle = (item: string) => {
      getExportSingle(item);
    };
    const handleSizeChange = (pageSize: number) => {
      queryForm.value.page = 1;
      queryForm.value.size = pageSize;
      getConsultantList(queryForm.value);
    };
    //督导表格
    const tableData_consultant = ref<any>([]);
    const queryForm_consultant = ref({
      page: 1,
      size: 9,
      role: 1,
      name: "",
    });
    const total_consultant = ref(0);
    const initConsultantTable = async () => {
      //重新定义一个queryForm
      const tmp = {
        page: queryForm_consultant.value.page - 1,
        size: queryForm_consultant.value.size,
        role: 1,
        name: queryForm_consultant.value.name,
      };
      const res = await getConsultantList(tmp);
      // console.log(res);
      const list = Array.from(res.data.result.counsellorList);
      list.forEach((val: any) => {
        if (val.isOnline == 1) {
          tableData_consultant.value.push(val);
        }
      });

      total_consultant.value = tableData_consultant.value.length;
      console.log(
        "tableData_consultant",
        tableData_consultant,
        total_consultant
      );
    };
    initConsultantTable();
    //分页器相关
    const handleCurrentChange_consultant = (pageNum: number) => {
      queryForm_consultant.value.page = pageNum;
      initConsultantTable();
    };

    const handleCurrentChange = (pageNum: number) => {
      queryForm.value.page = pageNum;
      getConsultantList(queryForm.value);
    };
    getPageInfo();
    return {
      queryForm,
      showCalendar,
      showData,
      tableText,
      imgUrl,
      showDialog,
      chatData,
      showTable,
      total_consultant,
      queryForm_consultant,
      tableData_consultant,
      dialog1,
      currentConsultant,
      selectColor,
      currentList,
      currentUser,
      initConsultantTable,
      handleSizeChange,
      handleCurrentChange,
      commmit,
      getDetails,
      showDetails,
      exportSingle,
      calendar,
      isSelect,
      getPageInfo,
      currentData,
      tableData,
      dealRecord,
      handleCurrentChange_consultant,
      value1,
    };
  },
});
</script>

<style scoped lang="less">
.homePage {
  width: 100%;
  height: 100%;
  position: relative;
  .info {
    display: flex;
    border: 1px;
    border-radius: 4px;
    box-shadow: 1px 1px 12px rgba(0, 0, 0, 0.175);
    position: relative;
    left: 20px;
    top: 1%;
    width: 50%;
    height: 20%;
    .avatar {
      display: block;
      width: 170px;
      height: 170px;
    }
    .rate {
      position: absolute;
      top: -122px;
      left: 192px;
    }
    .online {
      color: #fff;
      float: inherit;
      top: -150px;
      left: 403px;
      position: absolute;
    }
    .max-btn {
      position: absolute;
      width: 10px;
      bottom: 1px;
      left: 200px;
    }
    ::v-deep.el-dialog {
      width: 300px;
    }
  }
  .card-table {
    width: 50%;
    height: 25%;
    position: absolute;
    top: 45%;
    left: 20px;
    font-size: 10px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 18px;
      .head-title {
        margin-left: 32px;
      }
      .el-pagination {
        position: absolute;
        right: 40px;
      }
    }

    .el-row {
      margin-top: 10px;
      margin-left: 32px;
    }

    .card-item1 {
      position: relative;
      width: 150px;
      height: 60px;
      margin-right: 20px;
      background-image: linear-gradient(#64e66d, #d2e8db);
    }
    .card-item2 {
      position: relative;
      width: 150px;
      height: 60px;
      margin-right: 20px;
      background-image: linear-gradient(#64e66d, #d2e8db);
    }
    .card-item3 {
      position: relative;
      width: 150px;
      height: 60px;
      margin-right: 20px;
      background-image: linear-gradient(#64e66d, #d2e8db);
    }
    ::v-deep .card-table {
        margin-left: 0;
    }
  }
  .Scheduling {
    position: absolute;
    border: 1px;
    border-radius: 4px;
    box-shadow: 1px 1px 12px rgba(0, 0, 0, 0.175);
    right: 21px;
    top: 1%;
    width: 40%;
    height: 64%;
    :v-deep .el-calendar-table .el-calendar-day {
      width: 300px;
      height: 300px;
    }
    ::v-deep .el-calendar-table .el-calendar-day {
      height: 62px;
    }
  }
  .times {
    position: absolute;
    display: flex;
    border: 1px;
    border-radius: 4px;
    box-shadow: 1px 1px 12px rgba(0, 0, 0, 0.175);
    top: 22%;
    left: 20px;
    width: 50%;
    height: 20%;
    ::v-deep .el-table__header {
      height: 80px;
      font-size: 22px;
    }
    ::v-deep .el-table th.el-table__cell {
      text-align: center;
    }
    ::v-deep .el-table td {
      height: 80px;
      font-size: 26px;
    }
  }
  .record-table {
    position: absolute;
    border: 1px;
    border-radius: 4px;
    box-shadow: 1px 1px 12px rgba(0, 0, 0, 0.175);
    width: 100%;
    height: 200px;
    bottom: 50px;
    .item {
      ::v-deep .el-form-item__label {
        left: 21px;
        font-size: 17px;
        position: relative;
        top: 10px;
      }
      .detail {
        position: absolute;
        top: 10px;
        right: 50px;
      }
    }
    /*气泡*/
    .pop {
      position: relative;
      width: auto;
      height: auto;
      min-height: 35px;
      min-width: 30px;
      padding: 2px 15px;
      line-height: 33px;
      background: #fff;
      left: 25px;
      color: #fff;
      border-radius: 5px;
      background-color: #06b5eec2;
      /* border: 1.5px solid #4d4948; */
      text-align: center;
      margin-right: 30px;
    }
    /*尖角在左侧*/
    .pop .arrow {
      position: absolute;
      top: 5px;
      left: -16px;
      width: 0;
      height: 0;
      font-size: 0;
      border: solid 8px;
      border-color: #fff #06b5eec2 #fff #fff;
    }
  }
}
</style>
